<?php
class quesnrController extends AController {
	private $tableName = 'QUESTIONNAIRE';
	
	public function indexAction() {
		$select = array();
		$select['begtime'] = $bt = JYFilterUtils::unfilterText($this->request->getGetParameter('bt'));
		$select['endtime'] = $et = JYFilterUtils::unfilterText($this->request->getGetParameter('et'));
		$select['DEP_NO'] = $did = JYFilterUtils::unfilterText($this->request->getGetParameter('did'));
		$select['cat'] = $cid = JYFilterUtils::unfilterText($this->request->getGetParameter('cid'));
		$select['state'] = $state = JYFilterUtils::unfilterText($this->request->getGetParameter('state'));
		$select['title'] = $title = JYFilterUtils::unfilterText($this->request->getGetParameter('title'));
		if(isset($_POST['sel_sub'])){
			$select['begtime'] = $bt = JYFilterUtils::unfilterText($this->request->getPostParameter('begtime'));
			$select['endtime'] = $et = JYFilterUtils::unfilterText($this->request->getPostParameter('endtime'));
			$select['DEP_NO'] = $did = JYFilterUtils::unfilterText($this->request->getPostParameter('did'));
			$select['cat'] = $cid = JYFilterUtils::unfilterText($this->request->getPostParameter('cate'));
			$select['state'] = $state = JYFilterUtils::unfilterText($this->request->getPostParameter('state'));
			$select['title'] = $title = JYFilterUtils::unfilterText($this->request->getPostParameter('title'));
		}
		$page = $this->request->getGetParameter('p',1);
		$pagesize = $this->request->getGetParameter('ps',10);
		
		$alldep = JYDep::getZyDepts($this->unid);
		$allcate = $this->getQuesnrCategory();
		$tolNum = $this->getQuesnrTotalNum($select);
		$tolpage = ceil($tolNum[0]['NUM']/$pagesize);
		if($page>$tolpage || $page<1){
			$page = 1;
		}
		$allquesnr = $this->getAllQuesnr($page,$pagesize,$select);
		foreach ($alldep as $v) {
			$dep[$v['DEP_NO']] = $v['DEP_NAME'];
		}
		foreach ($allcate as $v) {
			$cate[$v['CID']] = $v['CN'];
		}
//		var_dump($allcate);
//		var_dump($dep);
		unset($allcate);
		unset($alldep);
		$this->bt = $bt;
		$this->et = $et;
		$this->did = $did;
		$this->cid = $cid;
		$this->state = $state;
		$this->page = $page;
		$this->pagesize = $pagesize;
		$this->tolNum = $tolNum[0]['NUM'];
		$this->tolpage = $tolpage;
		$this->title = $title;
		$this->allcate = $cate;
		$this->dep = $dep;
		$this->allquesnr = $allquesnr;
		return $this->render();
	}
	public function addAction() {
		if(isset($_POST['add_next'])){
			$qnn['title'] = $this->request->getPostParameter('q_name');
			if(empty($qnn['title'])){
				$this->alert('请输入问卷名称');exit;
			}
			$qnn['end_time'] = $this->request->getPostParameter('q_endtime');
			$qnn['cat'] = $this->request->getPostParameter('q_cate');
			$qnn['note'] = $this->request->getPostParameter('q_info');
			$qnn['DEP_NO'] = $this->request->getPostParameter('q_dep');
			$qnn['upd_time'] = date('Y-m-d H:i:s');
			$qnn['upd_user'] = $this->username;
			$qnn['create_time'] = date('Y-m-d H:i:s');
			$qnn['unit_id'] = $this->unid;
			$qnn['state'] = 1;
			if($row = $this->addQuestionnaire($qnn)){
				$this->redirect('/index.php?c=quesnr&a=addstep2&id='.$row);exit;
			}
			$this->alert('系统繁忙，请重试');exit;
		}
		$q_cate = $this->getQuesnrCategory();
		$alldep = JYDep::getZyDepts($this->unid);
		$this->dep = $alldep;
		$this->q_cate = $q_cate;
		return $this->render();
	}
	public function addstep2Action(){
		$id = $this->request->getGetParameter('id'); //问卷ID
		if(isset($_POST['add_tit'])){
			$titids = implode(',',$_POST['alltit']);
			$qnn['upd_time'] = date('Y-m-d H:i:s');
			$qnn['upd_user'] = $this->username;
			$qnn['q_ids'] = $titids;
			$qnn['state'] = 2;
			if($this->updQuestionnaire($id,$qnn)){
				$this->alert('问卷题目设置成功，回到问卷管理而发布即可!','/index.php?c=quesnr&a=showquest&id='.$id);exit;
			}
			$this->alert('系统繁忙，请重试');exit;
		}
		$all_cate = $this->getTitCategory();
		$all_tit = $this->getAllTit();
		foreach ($all_tit as $v){
			$tit[$v['CAT']][] = $v;
			$selId .= $v['Q_ID'].',';
		}
		foreach ($all_cate as $v) {
			$cate[$v['CID']]=$v['CN'];
		}
//=============编辑时用 beg=================//
		$checked = array();
		$check = $this->getCheckedTitById($id);
		if(!empty($check['Q_IDS'])){
			$checked = explode(',', $check['Q_IDS']);
		}
//=============编辑时用 end=================//
		$selId = trim($selId,',');
		$opt = $this->getAllOpt($selId);
		$this->cate = $cate;
		$this->tit = $tit;
		$this->opt = $opt;
		$this->qid = $id;
		$this->checked = $checked;
		unset($all_cate);
		unset($all_tit);
		return $this->render();
	}
	public function editAction() {
		$id = $this->request->getGetParameter('id'); //问卷ID
		if(isset($_POST['add_next'])){
			$qnn['title'] = $this->request->getPostParameter('q_name');
			if(empty($qnn['title'])){
				$this->alert('问卷名称不能为空');exit;
			}
			$qnn['end_time'] = $this->request->getPostParameter('q_endtime');
			$qnn['cat'] = $this->request->getPostParameter('q_cate');
			$qnn['note'] = $this->request->getPostParameter('q_info');
			$qnn['DEP_NO'] = $this->request->getPostParameter('q_dep');
			$qnn['upd_time'] = date('Y-m-d H:i:s');
			$qnn['start_time'] = '';
			$qnn['upd_user'] = $this->username;
			if($this->updQuestionnaire($id,$qnn)){
				$this->redirect('/index.php?c=quesnr&a=addstep2&id='.$id);exit;
			}
			$this->alert('系统繁忙，请重试');exit;
		}
		$quesnr = $this->getQuesnrByIn($id);
		if('3' == $quesnr['STATE']){
			$this->alert('该问卷已经发布，不能修改！');exit;
		}
		
		$q_cate = $this->getQuesnrCategory();
		$alldep = JYDep::getZyDepts($this->unid);
		$this->quesnr = $quesnr;
		$this->dep = $alldep;
		$this->q_cate = $q_cate;
		return $this->render('../tpl/quesnr/add.php');
	}
	public function issueAction() {
		$id = $this->request->getGetParameter('id'); //问卷ID
		$quesnr = $this->getQuesnrByIn($id);
		if('3' == $quesnr['STATE']){
			$this->alert('该问卷已经发布！');exit;
		}
		if(in_array($quesnr['STATE'], array('4','5'))){
			$this->alert('该问卷已经关闭，请重新修改后再发布！');exit;
		}
		$arr['start_time'] = date('Y-m-d H:i:s');
		$arr['upd_time'] = date('Y-m-d H:i:s');
		$arr['upd_user'] = $this->username;
		$arr['state']=3;
		if($this->updQuestionnaire($id, $arr)){
			$this->alert('发布成功');exit;
		}
		$this->alert('系统繁忙，请重试');exit;
	}
	public function closeAction() {
		$id = $this->request->getGetParameter('id'); //问卷ID
		$quesnr = $this->getQuesnrByIn($id);
		if(in_array($quesnr['STATE'], array('4','5'))){
			$this->alert('该问卷已经关闭！');exit;
		}
		$arr['upd_time'] = date('Y-m-d H:i:s');
		$arr['upd_user'] = $this->username;
		$arr['state']=5;
		if($this->updQuestionnaire($id, $arr)){
			$this->alert('关闭成功');exit;
		}
		$this->alert('系统繁忙，请重试');exit;
	}
	public function autocloseAction(){
		$this->autoCloseQuesnr();
		exit;
	}
	public function delAction() {
		$id = $this->request->getGetParameter('id'); //问卷ID
		$quesnr = $this->getQuesnrByIn($id);
		if($quesnr['STATE']=='3'){
			$this->alert('该问卷正在发布中，请先关闭后再删除！');exit;
		}
		$arr['upd_time'] = date('Y-m-d H:i:s');
		$arr['upd_user'] = $this->username;
		$arr['state']=0;
		if($this->updQuestionnaire($id, $arr)){
			$this->alert('删除成功');exit;
		}
		$this->alert('系统繁忙，请重试');exit;
	}
	public function showquestAction() { //显示问卷 以及 答卷
		$id = $this->request->getGetParameter('id'); //问卷ID
		$isan = $this->request->getGetParameter('an'); //是否是答题（区分显示和答卷）
		$sid = $this->request->getGetParameter('sid'); //答题结果ID
		$lookid = $this->request->getGetParameter('look'); //仅仅只是查看问卷
		
		$quesnr = $this->getQuesnrByIn($id);
		$qids = $quesnr['Q_IDS'];
		if(empty($qids)){
			echo "<script>alert('还没有添加任何问卷');window.close();</script>";
//			$this->alert('还没有添加任何问卷');
			exit;
		}
		$allQuest = $this->getAllTit('q_id in ('.$qids.')');
		$allOpt = $this->getAllOpt($qids);
		if(isset($_POST['sub_answer']) && !empty($isan)){  //用于提交回答的问卷
			$answer = $_POST['answer'];
			$upd['ATTEND_USER_ID'] = $this->request->getGetParameter('pid');
			$upd['ATTEND_USER'] = urldecode($this->request->getGetParameter('name'));
			$upd['ATTEND_CARD'] = $this->request->getGetParameter('card');
			$upd['ATTEND_PHONE'] = $this->request->getGetParameter('phone');
			$upd['ATTEND_EMAIL'] = $this->request->getGetParameter('email');
			$upd['RETRUN_VISIT_NO'] = $this->request->getGetParameter('vno');
			$upd['SURVEY_TYPE'] = $this->request->getGetParameter('type',1);
			$upd['QDETL'] = json_encode($answer);
			$upd['QUES_ID'] = $id;
			$upd['UNIT_ID'] = $this->unid;
			$upd['STATE'] = 1;
			$upd['ATTEND_TIME'] = date('Y-m-d H:i:s');
			$upd['SURVEY_TIME'] = date('Y-m-d H:i:s');
			$upd['USER_ID'] = CSM_USER_ID;
			$upd['USER_NAME'] = CSM_USER_NAME;
			if($retid = $this->insertSurvey($upd)){
				foreach ($allQuest as $v){
					$quests[$v['Q_ID']] = $v;
				}
				foreach ($allOpt as $v){
					$opts[$v['OID']] = $v;
				}
				foreach ($answer as $key=>$v){
					$arr = array();
					$arr['SURVEY_ID'] = $retid;
					$arr['QUES_ID'] = $id;
					$arr['UNIT_ID'] = $this->unid;
					$arr['Q_ID'] = $key;
					$arr['DEP_NO'] = $this->request->getGetParameter('depno');
					$arr['DEP_NAME'] = $this->request->getGetParameter('depname');
					$arr['DOC_NO'] = $this->request->getGetParameter('docno');
					$arr['DOC_NAME'] = $this->request->getGetParameter('docname');
					if($quests[$key]['QTYPE'] == 2){ //多选题
						foreach ($v as $k=>$value) {
							if($k==='input')continue;
							$arr['OPT_ID'] = $value;
							$arr['OPT_NAME'] = $opts[$v[$k]]['ONAME'];
							$arr['OPT_VALUE'] = $v['input'][$v[$k]]?$v['input'][$v[$k]]:'';
							$this->insertSurverDetl($arr);
						}
					}else{
						if($quests[$key]['QTYPE'] == 1){ //单选题
							$arr['OPT_ID'] = $v[0];
							$arr['OPT_NAME'] = $opts[$v[0]]['ONAME'];
							$arr['OPT_VALUE'] = $v['input'][$v[0]];
						}else{  // 填空题
							$arr['OPT_VALUE'] = $v[0];
						}
						$this->insertSurverDetl($arr);
					}
				}
				if(!empty($upd['ATTEND_PHONE'])){
					$alert = "答题成功，谢谢您的支持！";
					echo "<script>alert('{$alert}');window.close();</script>";exit;
					//$this->alert('答题成功，谢谢您的支持！','/index.php?c=quesnr&a=showquest&look=1&id='.$id.'&sid='.$retid);exit;
				}
				$alert = "答题成功，谢谢您的支持！";
				echo "<script>alert('{$alert}');window.close();</script>";exit;
				//$this->alert('答题成功，谢谢您的支持！','/index.php?c=quesnr&a=showquest&id='.$id.'&sid='.$retid);exit;
			}
			$this->alert('系统繁忙，请重试');exit;
		}
		if(!empty($sid)){
			$surveyInfo = $this->getSurverInfoById($sid); //答题结果
			$this->surveyinfo = json_decode($surveyInfo['QDETL'],true);
		}
		unset($qids); //对问题进行重新排序，按 单选-多选-单行文本-多行文本的顺序显示  $allQuest数值是按着QTYPE排序得到
		foreach ($allQuest as $v){
			$qids .= $v['Q_ID'].',';
			$quest[$v['Q_ID']]['QTYPE'] = $v['QTYPE'];
			$quest[$v['Q_ID']]['TITLE'] = $v['TITLE'];
			$quest[$v['Q_ID']]['ALLOW_NULL'] = $v['ALLOW_NULL'];
		}
		unset($allQuest);
		$optarr = ATools::getConfig('app.quesnr.tittype');
		$qids = explode(',', rtrim($qids,','));
		$this->id = $id;
		$this->sid = $sid;
		$this->look = $lookid;
		$this->qids = $qids;
		$this->allAquest = $quest;
		$this->allOpt = $allOpt;
		$this->quesnr = $quesnr;
		$this->optarr = $optarr;
		$this->isanswer = !empty($isan)?'yes':'no';
		return $this->render();
	}
	public function quesnrhistoryAction(){
		$pid = $this->request->getGetParameter('pid');
		$page = $this->request->getGetParameter('p',1);
		$pagesize = $this->request->getGetParameter('ps',4);
		
		if(empty($pid)){
			$this->alert('参数有误');exit;
		}
		$quesnr = $this->getAllQuesnrInfoByPid($pid,$page,$pagesize);
		$quesnrs = $this->getAllQuesnr(0,10,array());
		$tolNum = $this->getAllQuesnrNumByPid($pid);
		foreach ($quesnrs as $v){
			$ques[$v['QUES_ID']] = $v['TITLE'];
		}
		unset($quesnrs);
		$this->page = $page;
		$this->pagesize = $pagesize;
		$this->tolNum = $tolNum['NUM'];
		$this->ques = $ques;
		$this->quesnr = $quesnr;
		$this->pid = $pid;
		return $this->render();
	}
	function getTitCategory(){ //返回所有问卷题目分类信息
//		$key = md5(__FUNCTION__.$id.$page.$pagesize.$select);
//		if(JYMemcache::get($key)){
//			return unserialize(JYMemcache::get($key));
//		}
		if($this->unid<0){
			$where = 'state=1 and cat_type=2';
		}else{
			$where = 'state=1 and unit_id='.$this->unid.' and cat_type=2';
		}
		
		$fields = 'cat_id cid,cat_name cn';
		$order = 'upd_time desc';
		$data = JYDB::findAll('CATEGORY',$where,$fields,$order);
//		JYMemcache::set($key,serialize($data),60);
		return $data;
	}
	function getQuesnrCategory(){ //返回所有问卷题目分类信息
//		$key = md5(__FUNCTION__.$id.$page.$pagesize.$select);
//		if(JYMemcache::get($key)){
//			return unserialize(JYMemcache::get($key));
//		}
		if($this->unid<0){
			$where = 'state=1 and cat_type=1';
		}else{
			$where = 'state=1 and unit_id='.$this->unid.' and cat_type=1';
		}
		
		$fields = 'cat_id cid,cat_name cn';
		$order = 'upd_time desc';
		$data = JYDB::findAll('CATEGORY',$where,$fields,$order);
//		JYMemcache::set($key,serialize($data),60);
		return $data;
	}
	function getCheckedTitById($id){
		return JYDB::find($this->tableName,'ques_id='.$id,'q_ids');
	}
	function getAllTit($w=''){ //返回医院的所有题目
		if($this->unid<0){
			$where = 'state=1 ';
		}else{
			$where = 'unit_id='.$this->unid.' and state=1 ';
		}
		
		if(!empty($w)){
			$where .= 'and '.$w;
		}
//		echo $where;
		return JYDB::findAll('QUESTION',$where,'allow_null,qtype,q_id,title,cat','QTYPE');
	}
	function getQuesnrByIn($id){
		return JYDB::find($this->tableName,'ques_id='.$id);
	}
	function autoCloseQuesnr(){
		$sql = 'update QUESTIONNAIRE set state=4,upd_time=\''.date('Y-m-d H:i:s').'\',upd_user=\''.CSM_USER_NAME.'\' where state not in (4) and ques_id in (select ques_id from '.$this->tableName.' where end_time<\''.date('Y-m-d H:i:s').'\')';
		return JYDB::execute($sql);
	}
	function getAllQuesnr($page,$pagesize,$select){
		if($this->unid<0){
			$where = 'state>0';
		}else{
			$where = 'state>0 and unit_id='.$this->unid;
		}
		if(count($select)>0){
			foreach ($select as $k=>$v){
				if(!empty($v)){
					if($k=='begtime'){
						$where .= ' and start_time>\''.$v.'\'';
						continue;
					}
					if($k=='endtime'){
						$where .= ' and start_time<\''.$v.'\'';
						continue;
					}
					if($k=='title'){
						$where .= ' and '.$k.' like \'%'.$v.'%\'';
						continue;
					}
					$where .= ' and '.$k.'='.$v;
				}
			}
		}
//		echo $where;
		$order = 'state,end_time desc';
		return JYDB::findAll($this->tableName,$where,'*',$order,$page,$pagesize);
	}
	function getQuesnrTotalNum($select){
		
		if($this->unid<0){
			$where = 'state>0';
		}else{
			$where = 'state>0 and unit_id='.$this->unid;
		}
			if(count($select)>0){
				foreach ($select as $k=>$v){
					if(!empty($v)){
						if($k=='begtime'){
							$where .= ' and create_time>\''.$v.'\'';
							continue;
						}
						if($k=='endtime'){
							$where .= ' and create_time<\''.$v.'\'';
							continue;
						}
						if($k=='title'){
							$where .= ' and '.$k.' like \'%'.$v.'%\'';
							continue;
						}
						$where .= ' and '.$k.'='.$v;
					}
				}
			}
//			echo $where;
		return JYDB::findAll($this->tableName,$where,'count(*) num');
	}
	function getAllOpt($selId){
		$where = 'state=1 and q_id in ('.$selId.')';
		return JYDB::findAll('QUESTION_OPTIONS',$where,'opt_id oid,opt_name oname,allow_input input,q_id qid','allow_input desc,sort_no');
	}
	function getAllDep(){
		if($this->unid<0){
			$where = '1=1';
		}else{
			$where = 'unit_id='.$this->unid;
		}
		return JYDB::findAll('DEP',$where,'DEP_NO DID,DEP_NAME DN');
	}
	function getSurverInfoById($id){
		return JYDB::find('SURVEY','survey_id='.$id,'QDETL');
	}
	function getAllQuesnrInfoByPid($pid,$page,$pagesize){
		return JYDB::findAll('SURVEY','attend_user_id='.$pid,'*','',$page,$pagesize);
	}
	function getAllQuesnrNumByPid($pid){
		return JYDB::find('SURVEY','attend_user_id='.$pid,'count(*) num');
	}
	function updQuestionnaire($id,$arr){
		$where = 'ques_id='.$id;
		return JYDB::update($this->tableName,$where,$arr);
	}
	function addQuestionnaire($arr){
		return JYDB::create($this->tableName,$arr,'ques_id');
	}
	function insertSurvey($arr){
//		return 1;
		return JYDB::create('SURVEY',$arr,'survey_id');
	}
	function insertSurverDetl($arr){
		return JYDB::create('SURVEY_DETL',$arr,'ID');
	}
}